package plugins.openform;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.control.events.BeforeClickEvent;
import kd.bos.form.events.SetFilterEvent;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;
import java.util.Map;

/**
 * 标准单据列表插件
 */
public class OpenNewsHistory extends AbstractListPlugin implements Plugin {
    private static final String IDENTITY_PARAM = "Identity";
    private static final String USER_VALUE = "user";
    private static final String NEWS_EDITOR = "dcb4_news_editor";
    private static final String NEWS = "dcb4_news";
    private static final String USERNAME_FIELD = "dcb4_username";
    private static final String AUTHOR_FIELD = "dcb4_author";

    private boolean shouldApplyFilter = false;
    private String currentUser = null;

    @Override
    public void afterCreateNewData(EventObject e) {
        // 获取菜单入口参数
        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        String identity = (String) customParams.get(IDENTITY_PARAM);

        if (USER_VALUE.equals(identity)) {
            // 获取当前用户名
            currentUser = RequestContext.get().getUserName();

            // 检查dcb4_news_editor中是否存在匹配记录
            QFilter userFilter = new QFilter(USERNAME_FIELD, QCP.equals, currentUser);
            shouldApplyFilter = QueryServiceHelper.exists(NEWS_EDITOR, new QFilter[]{userFilter});

            if (!shouldApplyFilter) {
                this.getView().showMessage("当前用户没有编辑过任何新闻！");
            }
        }
        super.afterCreateNewData(e);
    }

    @Override
    public void setFilter(SetFilterEvent e) {
        super.setFilter(e);

        //  this.getView().showTipNotification("当前用户: " + currentUser);

        if (shouldApplyFilter && currentUser != null) {
            // 添加过滤条件
            QFilter authorFilter = new QFilter(AUTHOR_FIELD, QCP.equals, currentUser);
            e.addCustomQFilter(authorFilter);
        }
    }
}